import {Component, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup} from "@angular/forms";
import {ActivatedRoute} from "@angular/router";
import {Application} from "../shared/model/application";
import {DriverTableComponent} from "../shared/component/driver-table/driver-table.component";
import {VehicleTableComponent} from "../shared/component/vehicle-table/vehicle-table.component";
import {CamApplyService} from "../shared/service/cam-apply.service";
import {SingleOpenWinService} from "../shared/service/single-open-win.service";
import {Approve} from "../shared/model/approve";

@Component({
  selector: 'app-batch-assign',
  templateUrl: './batch-assign.component.html',
  styleUrls: ['./batch-assign.component.css']
})
export class BatchAssignComponent implements OnInit {

  applications:Application[] = [];
  vehicleForm:FormGroup;
  userId:string = this.routerInfo.snapshot.queryParams["userId"];
  @ViewChild(DriverTableComponent) driverTable:DriverTableComponent;
  @ViewChild(VehicleTableComponent) vehicleTable:VehicleTableComponent;

  //选择申请分页
  _current = 1;
  _pageSize = 10;
  _total = 1;
  _dataSet = [];

  //选择框
  _allChecked = false;
  // _indeterminate = false;
  _displayData: Array<any> = [];
  _checkedNumber = 0;
  _checkInfo= [];
  checkAllInfo = [];

  //选择车辆分页
  vehicleDataSet = [];

  saveFlag = true;  //防止重复提交

  //选择框
  vehicleDisplayData: Array<any> = [];

  constructor(
    private camApplyService:CamApplyService,
    private fb:FormBuilder,
    private singleOpenWinService:SingleOpenWinService,
    private routerInfo:ActivatedRoute,
  ) { }

  ngOnInit() {
    this.createForm();

    this.getDatas();

    //订阅车辆开窗
    this.singleOpenWinService.vehicleChange.subscribe((info:string)=>{
      $('#oid').val(this.vehicleTable.selected.vehicle.oid);
      $('#name').val(this.vehicleTable.selected.vehicle.name);
      $('#licenseNumber').val(this.vehicleTable.selected.vehicle.licenseNumber);
      if(this.vehicleTable.selected.vehicle.passengerCapacity){
        $('#passengerCapacity').val(this.vehicleTable.selected.vehicle.passengerCapacity);
      }else{
        $('#passengerCapacity').val("");
      }
      if(this.vehicleTable.selected.vehicletype){
        $('#vehicleType').val(this.vehicleTable.selected.vehicletype.oid);
        $('#vehicleTypeName').val(this.vehicleTable.selected.vehicletype.name);
      }else{
        $('#vehicleType').val("");
        $('#vehicleTypeName').val("");
      }
      if(this.vehicleTable.selected.driver){
        $('#driver').val(this.vehicleTable.selected.driver.oid);
        $('#driverName').val(this.vehicleTable.selected.driver.name);
        $('#driverPhone').val(this.vehicleTable.selected.driver.phone);
      }else{
        $('#driver').val("");
        $('#driverName').val("");
        $('#driverPhone').val("");
      }

      this.vehicleIsVisible = false;
    });

    //订阅司机开窗
    this.singleOpenWinService.driverChange.subscribe((info:string)=>{
      $('#driver').val(this.driverTable.selected.oid);
      $('#driverName').val(this.driverTable.selected.name);
      $('#driverPhone').val(this.driverTable.selected.phone);
      this.driverIsVisible = false;
    });

  }

  refreshData(reset = false) {
    if (reset) {
      this._current = 1;
    }
    // this._allChecked = false;
    this.getDatas();
  };

  _displayDataChange($event) {
    this._displayData = $event;
  };

  getDatas(){
    this.camApplyService.getApplications(this._current,this._pageSize).then(  res=>{
      this.applications = res.list;
      for(let i=0;i<this.applications.length;i++){
        if(this.applications[i].shared === 1){
          this.applications[i].sharedname = "是";
        }else{
          this.applications[i].sharedname = "否";
        }
        //判断是否已有派送车辆
        if(!this.applications[i].vehicleObj){
          this.applications[i].vehicleIsExist = false;
        }else{
          this.applications[i].vehicleIsExist = true;
        }

        //流程已结案并且不同意拼车，则不显示checkbox
        if(this.applications[i].shared === 0 && this.applications[i].status === 1){
          this.applications[i].chkIsExist = false;
        }else{
          this.applications[i].chkIsExist = true;
        }
      }
      this._dataSet = this.applications;
      this._total = res.total;
      this._displayData = this.applications;

      this.select(this.checkAllInfo,this._dataSet);
      this._refreshStatus("","");
      // console.log(this._dataSet);
    });
  }

  //当前页checkbox选中判断
  _refreshStatus(event,processsn) {
    this._checkedNumber = this._dataSet.filter(value => value.checked).length;
    this._checkInfo = this._dataSet.filter(value => value.checked);  //存放选中行的信息
    //去掉重复选择数据
    if(event==true){
      this.checkAllInfo = this.checkAllInfo.filter((r) => !(r.processsn === processsn));
      let selectInfo = this._dataSet.filter(value => value.processsn == processsn);
      let vehicleOid = "";
      if(selectInfo[0].vehicleIsExist){
        vehicleOid = selectInfo[0].vehicleObj.oid;
      }else{

      }
      let driver = "";
      let driverName = "";
      let driverPhone = "";
      if(selectInfo[0].driver){
        driver = selectInfo[0].driver;
        driverName = selectInfo[0].driverObj.name;
        driverPhone = selectInfo[0].driverObj.phone;
      }
      this.checkAllInfo.push({
        processsn:selectInfo[0].processsn,
        shared:selectInfo[0].shared,
        vehicleOid:vehicleOid,
        driverOid:driver,
        driverName:driverName,
        driverPhone:driverPhone,
        status:selectInfo[0].status
      });
      // console.log(this.checkAllInfo);
    }
    if(event == false){
      this.checkAllInfo = this.checkAllInfo.filter((r) => !(r.processsn === processsn));
    }
  };

  //选择判断
  select(selectedData:any,currentData:any){
    let selectInfo = [];
    if(selectedData){
      for(var i=0;i<currentData.length;i++){
        for(var j=0;j<selectedData.length;j++){
          if(currentData[i].processsn == selectedData[j].processsn){
            selectInfo.push(currentData[i]);
          }
        }
      }
      selectInfo.forEach(data => data.checked = true);
    }
  }

  createForm(){
    this.vehicleForm = this.fb.group({
      oid:'',
      name:'',
      vehicleType:'',
      vehicleTypeName:'',
      licenseNumber:'',
      passengerCapacity:'',
      driver:'',
      driverName:'',
      driverPhone:'',
      test:''
    });
  }

  /**
   * 单选司机开窗
   * @type {boolean}
   */
  driverIsVisible = false;

  driverShowModal = () => {
    this.driverIsVisible = true;
  }

  driverHandleCancel = (e) => {
    this.driverIsVisible = false;
  }

  //选择司机
  btn_select_driver(){
    this.driverTable.ngOnInit();
    this.driverShowModal();
  }

  /**
   * 单选车辆开窗
   * @type {boolean}
   */
  vehicleIsVisible = false;

  vehicleShowModal = () => {
    this.vehicleIsVisible = true;
  }

  vehicleHandleCancel = (e) => {
    this.vehicleIsVisible = false;
  }

  //选择司机
  btn_select_vehicle(){
    this.vehicleTable.ngOnInit();
    this.vehicleShowModal();
  }

  //按钮是否可编辑flag
  _disabledButton = true;
  _disabledButtonEdit = true;
  selected: any;
  rowindex:number = 0;

  //新增
  _operateDataAdd(){
    if(this.checkData("add")){
      let processsns = "";
      let shareds = "";
      let vehicleOids = "";
      let statuses = "";
      for(let i=0;i<this.checkAllInfo.length;i++){
        processsns += this.checkAllInfo[i].processsn+";";
        shareds += this.checkAllInfo[i].shared+";";
        vehicleOids +=this.checkAllInfo[i].vehicleOid+";";
        statuses +=this.checkAllInfo[i].status+";";
      }
      this.vehicleDataSet.push({
        key:this.rowindex++,
        oid:$('#oid').val(),
        name:$('#name').val(),
        vehicleType: $('#vehicleType').val(),
        vehicleTypeName:$('#vehicleTypeName').val(),
        licenseNumber:$('#licenseNumber').val(),
        passengerCapacity: $('#passengerCapacity').val(),
        driver: $('#driver').val(),
        driverName: $('#driverName').val(),
        driverPhone:$('#driverPhone').val(),
        processsns:processsns,
        shareds:shareds,
        vehicleOids:vehicleOids,
        statuses:statuses
      });
      // console.log(this.checkAllInfo);
      this.clearFormData();
    }
  }

  //修改
  _operateDataEdit(){
    if(this.checkData("edit")) {
      let processsns = "";
      let shareds = "";
      let vehicleOids = "";
      let statuses = "";
      for (let i = 0; i < this.checkAllInfo.length; i++) {
        processsns += this.checkAllInfo[i].processsn + ";";
        shareds += this.checkAllInfo[i].shared + ";";
        vehicleOids += this.checkAllInfo[i].vehicleOid + ";";
        statuses +=this.checkAllInfo[i].status+";";
      }
      let index = this.vehicleDataSet.findIndex(r => this.selected.key === r.key);
      this.vehicleDataSet[index].oid = $("#oid").val();
      this.vehicleDataSet[index].name = $("#name").val();
      this.vehicleDataSet[index].vehicleType = $("#vehicleType").val();
      this.vehicleDataSet[index].vehicleTypeName = $('#vehicleTypeName').val();
      this.vehicleDataSet[index].licenseNumber = $('#licenseNumber').val();
      this.vehicleDataSet[index].passengerCapacity = $('#passengerCapacity').val();
      this.vehicleDataSet[index].driver = $('#driver').val();
      this.vehicleDataSet[index].driverName = $("#driverName").val();
      this.vehicleDataSet[index].driverPhone =  $("#driverPhone").val();
      this.vehicleDataSet[index].processsns = processsns;
      this.vehicleDataSet[index].shareds = shareds;
      this.vehicleDataSet[index].vehicleOids = vehicleOids;
      this.vehicleDataSet[index].statuses = statuses;
      // console.log(this.checkAllInfo);
      this.clearFormData();
    }
  }

  //删除
  _operateDataDel(){
    if(confirm("确认删除吗？")) {
      this.vehicleDataSet = this.vehicleDataSet.filter((r) => r.key != this.selected.key);
      this.clearFormData();
    }
  }

  //车辆选择表格方法
  vehicleRefreshData(reset = false) {
    this._checkedNumber = this._dataSet.filter(value => value.checked).length;
    this._disabledButtonEdit = this._checkedNumber===1?false:true;
  };

  vehicleDisplayDataChange($event) {
    this._displayData = $event;
  };

  //新增修改表格数据卡控
  checkData(flag){
    let msg ="";
    if(!$("#name").val()){
      msg +=("请选择车辆信息！\n");
    }
    if(!$("#driverName").val()){
      msg +=("请选择司机信息！\n");
    }

    if(this.checkAllInfo.length>0){
      for(let i=0;i<this.checkAllInfo.length;i++){
        if(this.checkAllInfo[i].vehicleOid !="" && this.checkAllInfo[i].vehicleOid != $("#oid").val()){
          msg +=("已结案流程不可更改派车信息，请重新选择！\n");
          break;
        }
        if(this.checkAllInfo[i].vehicleOid !="" && this.checkAllInfo[i].driverOid != $("#driver").val()){
          msg +=(`已结案流程不可更改司机信息（姓名：${this.checkAllInfo[i].driverName}，手机尾号：${this.checkAllInfo[i].driverPhone.substring(this.checkAllInfo[i].driverPhone.length-4)}），请重新选择！\n`);
          break;
        }
      }

      if(this.checkAllInfo.length>1){
        for(let i=0;i<this.checkAllInfo.length;i++){
          if(this.checkAllInfo[i].shared === 0){
            msg +=("所选数据中存在不同意拼车的用车申请，请重新选择！\n");
            break;
          }
        }
      }else{
        if(this.checkAllInfo[0].vehicleOid !=""){
          msg +=("该申请单已派过车，请重新选择！\n");
        }
      }
    }else{
      msg +=("请至少选择一条车辆申请信息！\n");
    }

    if(this.vehicleDataSet.length>0){
      let numb:number;
      for(let i=0;i<this.vehicleDataSet.length;i++){
        for(let j=0;j<this.checkAllInfo.length;j++){
          numb = this.vehicleDataSet[i].processsns.indexOf(this.checkAllInfo[j].processsn);
          if(numb!=-1){
            if(flag == "edit" && this.selected.key!=this.vehicleDataSet[i].key){
              msg +=("用车申请单号："+this.checkAllInfo[j].processsn+"不能重复选择！\n");
            }
            if(flag != "edit"){
              msg +=("用车申请单号："+this.checkAllInfo[j].processsn+"不能重复选择！\n");
            }
          }
        }
      }
    }
    if(msg){
      alert(msg);
      return false;
    }else{
      return true;
    }
  }

  //清空栏位
  clearFormData(){
    this.vehicleForm.reset({
      oid:'',
      name:'',
      vehicleType:'',
      vehicleTypeName:'',
      licenseNumber:'',
      passengerCapacity:'',
      driver:'',
      driverName:'',
      driverPhone:''
    });
    this._checkInfo = [];
    this.checkAllInfo = [];
    this._current = 1;
    this.getDatas();
    this._disabledButtonEdit = true;
    this._disabledButton = true;
    this.selected = "";
  }

  onSelect(data){
    this._checkInfo = [];
    this.checkAllInfo = [];

    this._disabledButtonEdit = false;
    this._disabledButton = false;
    this.selected = data;

    this.vehicleForm.reset({
      oid:data.oid,
      name:data.name,
      vehicleType:data.vehicleType,
      vehicleTypeName:data.vehicleTypeName,
      licenseNumber:data.licenseNumber,
      passengerCapacity:data.passengerCapacity,
      driver:data.driver,
      driverName:data.driverName,
      driverPhone:data.driverPhone
    });

    let processsns = data.processsns.split(";");
    let shareds = data.shareds.split(";");
    let vehicleOids = data.vehicleOids.split(";");
    let drivers = data.driver;
    let statuses = data.statuses.split(";");
    let driverNames = data.driverName;
    let driverPhones =data.driverPhone;
    for(let i=0;i<processsns.length-1;i++){
      this.checkAllInfo.push({
        processsn:processsns[i],
        shared:Number(shareds[i]),
        vehicleOid:vehicleOids[i],
        driverOid:drivers,
        driverName:driverNames,
        driverPhone:driverPhones,
        status:Number(statuses[i])
      });
    }

    this._current = 1;
    this.getDatas();
  }

  onSubmit(){
    if(this.vehicleDataSet.length<=0){
      alert("请添加最少一笔数据！");
      return false;
    }else if(!this.userId ){
      alert("流程审批人不能为空");
    }else{
      if(this.saveFlag) {
        this.saveFlag = false;
        // console.log(this.vehicleDataSet);
        let approve: Approve[] = [];
        let processsns = [];
        let statuses = [];
        for (let i = 0; i < this.vehicleDataSet.length; i++) {
          processsns = this.vehicleDataSet[i].processsns.split(";");
          statuses = this.vehicleDataSet[i].statuses.split(";");
          for (let j = 0; j < statuses.length - 1; j++) {
            if (Number(statuses[j]) === 0) {
              approve.push({
                processsn: processsns[j], vehicle: this.vehicleDataSet[i].oid, driver: this.vehicleDataSet[i].driver
              });
            }
          }
        }
        console.log(approve);
        this.camApplyService.batchApprove(approve, this.userId).then(res => {
          if (res.code === 1) {
            alert(res.message);
            this.saveFlag = true;
            this.clearFormData();
            this.vehicleDataSet = [];
          } else {
            alert(res.message);
          }
        });
      }
    }
  }
}
